
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <iostream>


void read_routine(int sock,char *buf,int size)
{
    while(true)
    {
        int n = recv(sock,buf,size,0);
        if(n == 0)
        {
            std::cout << "服务器连接关闭!退出!" << std::endl;
            return;
        }
        buf[n] = 0;
        std::cout << "收到服务器消息: " << buf << std::endl;
    }
}

void write_routine(int sock,char *buf)
{
    while(true)
    {
        std::cin >> buf;
        if(!strcmp(buf,"Q") || !strcmp(buf,"q"))
        {
            //close(sock);
            shutdown(sock,SHUT_WR);
            return;
        }
        send(sock,buf,strlen(buf),0);
    }
}
int main()
{

	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	
	sockaddr_in server;
	memset(&server, 0, sizeof(server));
	server.sin_addr.s_addr = inet_addr("120.27.236.117");
	server.sin_family = AF_INET;
	server.sin_port = htons(9090);

	connect(sockfd, (const sockaddr*)&server, sizeof(server));
    char buffer[1024] = {0};
	pid_t id = fork();
    if(id == 0)
    {
        read_routine(sockfd,buffer,sizeof(buffer));
    }
    else 
    {
        write_routine(sockfd,buffer);
    }

    close(sockfd);
    return 0;
}